package cn.wp.org.service.impl;

import cn.wp.basic.service.impl.BaseServiceImpl;
import cn.wp.org.domain.Department;
import cn.wp.org.mapper.DepartmentMapper;
import cn.wp.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.save(department);
        if (department.getParent() == null || department.getParent().getId() == null){
            department.setDirPath("/"+department.getId());
        } else {
            // 获取上级部门的id
            Long parent_id = department.getParent().getId();
            // 获取上级部门的dirPath
            String parent_dirPath = departmentMapper.loadOne(parent_id).getDirPath();
            // 设置对象的dirPath值
            department.setDirPath(parent_dirPath + "/" + department.getId());
        }
        departmentMapper.update(department);
        // int a=1/0;// 测试事务
    }

    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent() == null || department.getParent().getId() == null){
            department.setDirPath("/"+department.getId());
        } else {
            // 获取上级部门的id
            Long parent_id = department.getParent().getId();
            // 获取上级部门的dirPath
            String parent_dirPath = departmentMapper.loadOne(parent_id).getDirPath();
            // 设置对象的dirPath值
            department.setDirPath(parent_dirPath + "/" + department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void patchDel(List<Long> ids) {
        departmentMapper.patchDel(ids);
    }

    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();
    }

}
